package fragments;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.example.administrator.baseproject.BaseFragment;
import com.example.administrator.newxlmedical.EnterActivity;
import com.example.administrator.newxlmedical.MainActivity;
import com.example.administrator.newxlmedical.R;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import beans.TerminalEnableBean;
import beans.TokenBean;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import netframe.GetRetrofit;
import netframe.MyAction1;
import netframe.NetReconnectFunc1;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.observables.GroupedObservable;
import rx.schedulers.Schedulers;
import utils.ActivityUtil;
import utils.HardwareInfoUtils;
import utils.TimeUtil;
import utils.ToastUtil;

/**
 * Created by Administrator on 2018/5/16.
 */

public class TerminalPasswordFragment extends BaseFragment {

    @BindView(R.id.et_terminal_password)
    EditText etPassword;
    @BindView(R.id.btn_terminal_password_terminal)
    Button btnTerminalPasswordTerminal;
    @BindView(R.id.btn_terminal_password_return)
    Button btnTerminalPasswordReturn;
    Unbinder unbinder;
    @BindView(R.id.et_terminal_password_error)
    TextView etError;
    private TerminalPasswordInterface passwordInterface;
    private String hospitalName;
    private String hospitalAddress;
    private String hospitalDepartments;
    private String hospitalRemark;
    private String departmentCode;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (activity instanceof TerminalPasswordInterface) {
            passwordInterface = (TerminalPasswordInterface) activity;
        } else {
            throw new IllegalArgumentException("activity must implements TerminalInfoInterface");
        }

        Bundle arguments = getArguments();
        hospitalRemark = arguments.getString("Remark");
        hospitalName = arguments.getString("Name");
        hospitalDepartments = arguments.getString("Departments");
        hospitalAddress = arguments.getString("Address");
        departmentCode = arguments.getString("departmentCode");

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_terminal_password, null);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.btn_terminal_password_terminal, R.id.btn_terminal_password_return})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_terminal_password_terminal:
                String password = etPassword.getText().toString().trim();
                if (TextUtils.isEmpty(password)) {
                    ToastUtil.showToast(mContext, "密码不能为空!");
                }else {
                    btnTerminalPasswordTerminal.setClickable(false);
                    sure(password);
                }
                break;
            case R.id.btn_terminal_password_return:
                passwordInterface.back();
                break;
        }

    }

    public interface TerminalPasswordInterface {
        void back();

        void sure(String id, String tokenCode, String machineCode,String deptCode);
    }

    private void sure(final String passwrod) {
        GetRetrofit.getRetrofit().getToken("select * from Token where MachineCode = '" + HardwareInfoUtils.getMachineCode(mContext) + "'").subscribeOn(Schedulers.io()).retryWhen(new NetReconnectFunc1()).groupBy(new Func1<List<TokenBean>, Boolean>() {
            @Override
            public Boolean call(List<TokenBean> tokenBeen) {
                return tokenBeen == null ? false : tokenBeen.size() != 0;
            }
        }).observeOn(AndroidSchedulers.mainThread()).onTerminateDetach().flatMap(new Func1<GroupedObservable<Boolean, List<TokenBean>>, Observable<TokenBean>>() {
            @Override
            public Observable<TokenBean> call(GroupedObservable<Boolean, List<TokenBean>> booleanListGroupedObservable) {
                if (booleanListGroupedObservable.getKey()) {
                    //已经被激活过，
                    return booleanListGroupedObservable.observeOn(Schedulers.io()).flatMap(new Func1<List<TokenBean>, Observable<TokenBean>>() {
                        @Override
                        public Observable<TokenBean> call(List<TokenBean> tokenBeen) {
                            return Observable.from(tokenBeen).last();
                        }
                    });
                } else {
                    //还没有被激活过
                    terminalEnable(passwrod, hospitalName, hospitalDepartments, hospitalAddress, hospitalRemark);
                    return null;
                }
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<TokenBean>() {
            @Override
            public void call(TokenBean tokenBean) {
                btnTerminalPasswordTerminal.setClickable(true);
                ToastUtil.showToast(mContext, "激活成功");
                passwordInterface.sure(String.valueOf(tokenBean.getTerminalInfoId()), tokenBean.getTokenCode(), tokenBean.getMachineCode(),departmentCode);
            }
        }, new MyAction1() {
            @Override
            public void call(Throwable throwable) {
                super.call(throwable);
                btnTerminalPasswordTerminal.setClickable(true);
                ToastUtil.showToast(mContext, "网络请求错误");
            }
        });
    }

    private void terminalEnable(String dialogPassword, String dialogHospital, String dialogDepartment, String dialogAddress, String dialogRemark) {

        Map<String, String> map = new HashMap<String, String>();
        map.put("Address", dialogAddress);
        map.put("password", dialogPassword);
        map.put("DeleteFlag", "0");
        map.put("Department", dialogDepartment);
        map.put("HospName", dialogHospital);
        map.put("Reamrk", dialogRemark);
        map.put("MachineCode", HardwareInfoUtils.getMachineCode(mContext));
        map.put("SubTime", TimeUtil.getMillisecondDate());
        map.put("DeptCode", departmentCode);
        GetRetrofit.getInstance().terminalEnable(map).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<TerminalEnableBean>() {
            @Override
            public void call(TerminalEnableBean terminalEnableBean) {
                if (!TextUtils.isEmpty(terminalEnableBean.getTokenCode())) {
                    btnTerminalPasswordTerminal.setClickable(true);
                    ToastUtil.showToast(mContext, "激活成功");
                    passwordInterface.sure(String.valueOf(terminalEnableBean.getID()), terminalEnableBean.getTokenCode(), terminalEnableBean.getMachineCode(),terminalEnableBean.getDeptCode());
                } else {
                    btnTerminalPasswordTerminal.setClickable(true);
                    etError.setVisibility(View.VISIBLE);
                }
            }
        }, new MyAction1());

    }

}
